package repositories

import (
	"gitee.com/cjf8134/bbs_serve/internal/pkg/models"
	"gitee.com/cjf8134/bbs_serve/internal/pkg/requests"
	"gitee.com/cjf8134/bbs_serve/internal/pkg/utils/constutil"
	"github.com/jinzhu/gorm"
	"github.com/pkg/errors"
)

// CommentZanNum  点赞 +1
func (r *MysqlApiServeRepository) CommentZanNum(CommentID int, num int) (err error) {
	model := r.db.Model(models.Comment{})
	model = model.Where("id = ?", CommentID)
	err = model.UpdateColumns(map[string]interface{}{
		"zan_num": gorm.Expr("zan_num + ?", num),
	}).Error
	return
}

// Comment  回复
func (r *MysqlApiServeRepository) Comment(req *requests.Comment) (err error) {
	tx := r.db.Begin()
	var value                             models.Comment
	model := tx.Model(models.Comment{})
	value = models.Comment{
		Content:  req.Content,
		Username: req.Username,
		Avatar:   req.Avatar,
		ThreadID: req.ThreadID,
	}
	err = model.Create(value).Error
	if err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()
	return
}

// CommentZan  点赞
func (r *MysqlApiServeRepository) CommentZan(req *requests.CommentZan) (err error) {
	model := r.db.Model(models.Zan{})
	var zan models.Zan
	model.Where("id = ?", req.CommentID).Where("user_id = ?", req.UserID).First(&zan)
	if zan.CommentID > 0 {
		err = errors.New("当前记录已点赞.")
		return
	}
	value := models.Zan{
		UserID:    req.UserID,
		CommentID: req.CommentID,
	}
	err = model.Create(&value).Error
	return
}

// CommentList  回复列表
func (r *MysqlApiServeRepository) CommentList(req *requests.CommentList) (commentList []*models.Comment, err error) {
	model := r.db.Model(models.Comment{}).Where("thread_id = ?", req.ThreadID)
	if req.Limit <= 0 {
		req.Limit = constutil.DefaultMaxPageSize
	}
	if req.Limit > constutil.DefaultMaxPageSize {
		req.Limit = constutil.DefaultMaxPageSize
	}
	req.Page = req.Page - 1
	if req.Page <= 0 {
		req.Page = 0
	}
	order := "id desc"
	err = model.Offset(req.Page * req.Limit).Order(order).Limit(req.Limit).Find(&commentList).Error
	return
}

// CommentList  回复列表
func (r *MysqlApiServeRepository) CommentThreadList(req *requests.UserThread) (count int64, threadList []*models.Thread, err error) {
	var (
		threadIDs []int
	)
	model := r.db.Model(models.Comment{}).Where("username = ?", req.Username).Group("thread_id")
	if req.Limit <= 0 {
		req.Limit = constutil.DefaultMaxPageSize
	}
	if req.Limit > constutil.DefaultMaxPageSize {
		req.Limit = constutil.DefaultMaxPageSize
	}
	req.Page = req.Page - 1
	if req.Page <= 1 {
		req.Page = 0
	}
	order := "id desc"
	err = model.Offset(req.Page*req.Limit).Order(order).Limit(req.Limit).Pluck("thread_id", &threadIDs).Error
	model.Count(&count)
	if err != nil || len(threadIDs) == 0 {
		return
	}
	err = r.db.Model(models.Thread{}).Where("id in (?)", threadIDs).Find(&threadList).Error
	return
}
